package com.app.oral.config

import com.app.oral.model.ExerciseStatus
import org.apache.ibatis.type.BaseTypeHandler
import org.apache.ibatis.type.JdbcType
import org.apache.ibatis.type.MappedTypes
import java.sql.CallableStatement
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.SQLException

@MappedTypes(ExerciseStatus::class)
class ExerciseStatusTypeHandler : BaseTypeHandler<ExerciseStatus>() {

    @Throws(SQLException::class)
    override fun setNonNullParameter(ps: PreparedStatement, i: Int, parameter: ExerciseStatus, jdbcType: JdbcType?) {
        ps.setString(i, parameter.value)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(rs: ResultSet, columnName: String): ExerciseStatus? {
        val value = rs.getString(columnName)
        return map(value)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(rs: ResultSet, columnIndex: Int): ExerciseStatus? {
        val value = rs.getString(columnIndex)
        return map(value)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(cs: CallableStatement, columnIndex: Int): ExerciseStatus? {
        val value = cs.getString(columnIndex)
        return map(value)
    }

    private fun map(value: String?): ExerciseStatus? {
        if (value == null) return null
        return when (value.lowercase()) {
            "not_started" -> ExerciseStatus.NOT_STARTED
            "in_progress" -> ExerciseStatus.IN_PROGRESS
            "completed" -> ExerciseStatus.COMPLETED
            else -> ExerciseStatus.IN_PROGRESS
        }
    }
}

